﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Xml.Serialization;

namespace BDSim
{
    /* by tzf 2014.04.05版*/
    /// <summary>
    /// 文件操作服务 
    /// </summary>
    public static class XmlFileOperater<T>
    {
        /// <summary>
        /// 从指定路径的文件中读取一个T类型的实例 
        /// </summary>
        /// <param name="path">xml文件路径</param>
        /// <returns></returns>
        public static T LoadFromFile(string path)
        {
            FileStream fs = null;
            T result = default(T);
            try
            {
                fs = new FileStream(path, FileMode.Open);
                XmlSerializer xs = new XmlSerializer(typeof(T));
                result = (T)xs.Deserialize(fs);
            }
            catch (Exception e)
            {
                System.Diagnostics.Trace.WriteLine(e.ToString());
                throw e;
            }
            finally
            {
                if (fs != null)
                    fs.Close();
            }
            return result;
        }

        /// <summary>
        /// 保存一个T类型的实例到指定路径的xml文件，若文件存在则覆盖 
        /// </summary>
        /// <param name="path">xml保存路径</param>
        /// <param name="data">要保存的T类型的一个数据</param>
        public static void SaveToFile(string path, T data)
        {
            FileStream fs = null;
            try
            {
                fs = new FileStream(path, FileMode.Create);
                XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
                ns.Add("", "");

                XmlSerializer xs = new XmlSerializer(typeof(T));
                xs.Serialize(fs, data, ns);
            }
            catch (Exception e)
            {
                System.Diagnostics.Trace.WriteLine(e.ToString());
                throw e;
            }
            finally
            {
                if (fs != null)
                    fs.Close();
            }
        }
    }
}